<template>
  <div id="app" style="overflow: hidden;width:100%;height:100%;">
    <vxe-grid ref="xGrid" v-bind="grid_options" :row-config="{height:36}" @form-reset="formResetEvent">
      <template #toolbar>
        <el-button type="primary" :size="size" icon="fa fa-plus" @click="addRowModal">新增</el-button>
        <el-button type="primary" :size="size" icon="fa fa-edit (alias)" @click="editRowModal">编辑</el-button>
        <el-button type="primary" :size="size" icon="fa fa-trash-o" @click="handleDelete">删除</el-button>
        <el-button type="primary" :size="size" icon="fa fa-trash-o" @click="handleAuditall">批量审核</el-button>
        <el-button type="primary" :size="size" icon="fa fa-trash-o" @click="handleAuditPass">审核</el-button>
      </template>
    </vxe-grid>
    <godownEntry ref="godownEntry" @closeEvent="closeEvent"></godownEntry>
    <auditEquipment ref="auditEquipment" @closeShEvent="closeShEvent"></auditEquipment>
    <equipmentList ref="equipmentList" @closeShEvent="closeShEvent"></equipmentList>
  </div>


</template>

<script>
import godownEntry from './components/godownEntry.vue'
import auditEquipment from './components/auditEquipment.vue'
import equipmentList from './components/equipmentList.vue'
import {godownEntryApi} from "@/api/equip/godownEntryApi";
import {warehouseManagement} from '@/api/equip/warehouseManagement.js'
import {CommonApi} from '@/api/equip/CommonApi'
import util from '@/utils/util'
import {getInfo} from "@/api/login";
import {listDept} from "@/api/system/dept";
import VXETable from "vxe-table";

export default {
  name: 'godownEntryIndex',
  components: {godownEntry, auditEquipment, equipmentList},
  data() {
    return {
      time: '',
      etime: '',
      enableDefault: true,
      LanderId: '',
      size: 'small',
      grid_options: {
        border: true,
        stripe: true,
        showHeaderOverflow: false,
        showOverflow: true,
        keepSource: true,
        id: 'full_edit_1',
        height: 700,
        rowId: 'id',  //指定记录主键
        rowConfig: {
          isHover: true
        },
        columnConfig: {
          resizable: true
        },
        customConfig: {
          storage: true,
          // checkMethod: this.checkColumnMethod
        },
        sortConfig: {
          trigger: 'cell',
          remote: true
        },
        filterConfig: {
          remote: true
        },
        formConfig: {
          form: true, // 启用表单代理
          size: "medium",        //尺寸
          titleAlign: "right",  //所有项的标题对齐方式
          titleWidth: "120", //标题宽度
          titleColon: true,     //是否显示标题冒号
          items: [
            {
              field: 'ssdwbm',
              title: '单位:',
              span: 6,
              itemRender: {
                name: '$select',
                options: [],
                props: {placeholder: '---请选择单位---'},
                events: {change: this.gldwbmChangeEvent}
              },
            },
            {
              field: 'id',
              title: '入库单号:',
              span: 6,
              itemRender: {name: '$input', props: {placeholder: '请输入入库单号'}},
            },
            {
              field: 'djshzt',
              title: '单据状态:',
              span: 6,
              itemRender: {name: '$select', options: [], props: {placeholder: '---请选择设备状态---'}}
            },
            {
              field: 'ckbm',
              title: '库房名称:',
              span: 6,
              itemRender: {name: '$select', options: [], props: {placeholder: '---请选择仓库名称---'}},
              folding: true,
            },
            {
              field: 'djrq',
              title: '入库日期',
              span: 6,
              itemRender: {name: '$input', props: {type: 'date'}},
              folding: true,
            },
            {
              field: 'djrq_to',
              title: '至',
              span: 6,
              itemRender: {name: '$input', props: {type: 'date'}},
              folding: true,
            },
            {
              span: 6, collapseNode: true, align: 'right', itemRender: {
                name: '$buttons', children: [
                  {props: {type: 'submit', content: '查询', status: 'primary', icon: 'fa fa-search'}},
                  {props: {type: 'reset', content: '重置', icon: 'fa fa-reply'}},
                ]
              }
            }
          ]
        },
        toolbarConfig: {
          buttons: [
            {buttonRender: {name: 'add', events: {click: this.addRowModal}}}, // 新增
            {buttonRender: {name: 'edit', events: {click: this.editRowModal}}},//编辑
            {buttonRender: {name: 'delete', events: {click: this.handleDelete}}},//删除
            {buttonRender: {name: 'auditall', events: {click: this.handleAuditall}}},//批量审核
            {buttonRender: {name: 'auditpass', events: {click: this.handleAuditPass}}},//审核
          ],
          slot: {
            buttons: 'toolbar'
          },
          refresh: true,
          custom: true,
        },
        pagerConfig: {
          pageSize: 10,
          pageSizes: [5, 10, 15, 20, 50, 100],
          layouts: ['PrevJump', 'PrevPage', 'JumpNumber', 'NextPage', 'NextJump', 'Sizes', 'FullJump', 'Total'],
          background: true,
        },
        proxyConfig: {
          seq: true, // 启用动态序号代理，每一页的序号会根据当前页数变化
          sort: true, // 启用排序代理，当点击排序时会自动触发 query 行为
          filter: true, // 启用筛选代理，当点击筛选时会自动触发 query 行为
          form: true, // 启用表单代理，当点击表单提交按钮时会自动触发 reload 行为
          // 对应响应结果 { result: [], page: { total: 100 } }
          props: {
            result: 'data.records', // 配置响应结果列表字段
            total: 'data.total' // 配置响应结果总页数字段
          },
          // 只接收Promise，具体实现自由发挥
          ajax: {
            // 当点击工具栏查询按钮或者手动提交指令 query或reload 时会被触发
            query: async ({page, sorts, filters, form}) => {
              // =====给表单项赋初始值======
              await this.initFormData(form);
              //    this.enableDefault = false;
              const queryParams = Object.assign({}, form)
              // const queryParams = this.initFormData(form)
              // 处理排序条件
              const firstSort = sorts[0]
              if (firstSort) {
                queryParams.sort = firstSort.property
                queryParams.order = firstSort.order
              }
              // 处理筛选条件

              filters.forEach(({property, values}) => {
                queryParams[property] = values.join(',')
              })
              return this.queryData(page, queryParams)
            },
          }
        },
        columns: [
          {type: 'seq', title: '序号', width: "60px", align: 'center', headerAlign: 'center'},
          {type: 'checkbox', width: "60px", align: 'center', headerAlign: 'center', visible: true},
          {
            field: 'audit',
            title: '操作',
            minWidth: "120px",
            align: 'center',
            headerAlign: 'center',
            cellRender: {name: 'audit', events: {click: this.handleAudit}}
          },
          {field: 'ssdwmc', title: '单位', minWidth: "160px", align: 'center', headerAlign: 'center',},
          {
            field: 'id',
            title: '入库单号',
            minWidth: "180px",
            align: 'center',
            headerAlign: 'center',
            cellRender: {name: 'rkdh', events: {click: this.handleAuditPass}}
          },
          {field: 'djrq', title: '入库日期', minWidth: "160px", align: 'center', headerAlign: 'center',},
          {
            field: 'sl',
            title: '入库数量',
            minWidth: "160px",
            align: 'center',
            headerAlign: 'center',
            cellRender: {name: 'sl', events: {click: this.handleAuditList}}
          },
          {field: 'djshztmc', title: '单据状态', minWidth: "160px", align: 'center', headerAlign: 'center',},
          {field: 'ckmc', title: '库房名称', minWidth: "160px", align: 'center', headerAlign: 'center'},
          {field: 'shPerson', title: '审核人', minWidth: "160px", align: 'center', headerAlign: 'center',},
          {field: 'shTime', title: '审核时间', minWidth: "160px", align: 'center', headerAlign: 'center',},
          {field: 'shyj', title: '审核意见', minWidth: "100px", align: 'center', headerAlign: 'center',},
        ],
        checkboxConfig: {
          // labelField: 'id',
          reserve: true,
          highlight: true,
          range: true
        },
        editConfig: {
          trigger: 'click',
          mode: 'row',
          showStatus: true
        }
      },
      djztOptions: [],
      rowDjshzt: false
      //  api: 'fetchQueryQueryRwxqByPage',
      // init: true
    }
  },
  computed: {
    options() {
      return {
        djztOptions: this.djztOptions,
        kfOptions: this.kfOptions
      }
    }
  },
  created() {
    // this.setReadModel()

  },
  mounted() {

    this.$nextTick(function () {
      this.fetchdjztOptions()
      this.fetchgldwOptions()
      // this.getKfOptions()
      this.setReadModel() //数据初始化
    })
    window.addEventListener('resize', this.setTableHeight);
  },
  destroyed: function () {
    window.removeEventListener('resize', this.setTableHeight);
  },
  methods: {
    // 高度自适应
    setTableHeight: function () {
      const tableContainer = document.querySelector("#app");
      const height = tableContainer.clientHeight;
      this.grid_options.height = height - 5;
    },
    initFormData(form) {

      const that = this;
      let datatime = new Date()
      if (that.enableDefault) {
        // 查询框默认值初识化
        if (this.row !== undefined) {
          form.djrq = this.formData.jhkssj
          form.djrq_to = this.formData.endTime
        } else {
          form.djrq = this.timeformat(datatime, 0, 'start')
          form.djrq_to = this.timeformat(datatime, 0, 'end')
        }
        this.enableDefault = false;

      }

    },
    //查询控制
    setReadModel() { //控制是否显示
      const isRead = util.isReadModel()
      if (isRead) {
        // this.grid_options.toolbarConfig.buttons=[{ buttonRender: { name: 'auditpass', events: { click: this.handleAuditPass } } }]
        this.grid_options.toolbarConfig.buttons = []
        let columns2
        this.$nextTick(() => {
          columns2 = this.$refs.xGrid.getColumns()
        })
        setTimeout(() => {
          // 将指定列设置为隐藏状态
          columns2.forEach(column => {

            if ('checkbox' == column.type) {
              column.visible = false
            }
          })
          if (this.$refs.xGrid) {
            this.$refs.xGrid.refreshColumn()
          }

        }, 100)
      }
      let type = util.getRequestParms('type')
      if (type == 'search') {
        this.grid_options.columns[1].visible = false
        this.grid_options.columns[2].visible = false
      }
      let time = util.getRequestParms('time')
      let etime = util.getRequestParms('etime')
      if (time) {
        this.time = time
        this.etime = etime
        this.$refs.xGrid._data.formData.djrq = time
        this.$refs.xGrid._data.formData.djrq_to = etime
      }


    },
    formResetEvent({data}) {
      let datatime = new Date()
      if (this.time) {
        data['djrq'] = this.time
        data['djrq_to'] = this.etime
      } else {
        data['djrq'] = this.timeformat(datatime, 0, 'start')
        data['djrq_to'] = this.timeformat(datatime, 0, 'end')
      }

      const item = this.$refs.xGrid.getFormItems(3)
      item.itemRender.options = []
    },

    timeformat(dat, value, type) {
      let year = dat.getFullYear();
      let mon = (dat.getMonth() + 1) < 10 ? "0" + (dat.getMonth() + 1) : dat.getMonth() + 1;
      let data = dat.getDate() < 10 ? "0" + (dat.getDate() - value) : dat.getDate() + value;
      if (type === 'start') {
        var newDate = year + "-" + mon + "-" + data;
      } else {
        var newDate = year + "-" + mon + "-" + data;
      }
      return newDate;
    },
    fetchdjztOptions() {
      CommonApi.queryDictData('EN_CRK_STATE').then(res => {
        // if (res.code === '200') {
        let optionList = [
          {label: '请选择', value: ''}
        ]
        res.data.forEach((item) => {
          optionList.push({label: item.value, value: item.code})
        })
        this.djztOptions = optionList
        const item = this.$refs.xGrid.getFormItems(2)
        item.itemRender.options = optionList
      })
    },
    fetchgldwOptions() {
      getInfo().then(res => {
        this.LanderId = res.user.userId
        var obj = {
          deptId: res.user.dept.deptId,
          parentId: res.user.dept.parentId
        }
        listDept().then(res => {
          let optionList = [
            {label: '请选择', value: ''}
          ]
          res.data.forEach((item) => {
            optionList.push({label: item.deptName, value: item.deptId})
          })
          this.djztOptions = optionList
          const item = this.$refs.xGrid.getFormItems(0)
          item.itemRender.options = optionList
        })
      })
    },
    gldwbmChangeEvent(value) {
      this.$refs.xGrid._data.formData.ckbm = null

      warehouseManagement.getKfByGldw(value.data.ssdwbm).then(res => {
        // 修改编辑框
        // const sexColumn = $grid.getColumnByField('sex')
        // sexColumn.editRender.options = sexList
        // 修改查询条件列表
        let optionList = [
          {label: '请选择', value: ''}
        ]
        res.data.forEach((item) => {
          // console.log(item,'item.,,,');
          optionList.push({label: item.kfName, value: item.id})
        })
        const item = this.$refs.xGrid.getFormItems(3)
        item.itemRender.options = optionList
      })
    },
    queryData: (page, formData) => {
      const queryParams = {
        pageSize: page.pageSize,
        pageNo: page.currentPage,
        entity: {
          ssdwbm: formData.ssdwbm ? formData.ssdwbm : null,
          id: formData.id ? formData.id : null,
          djshzt: formData.djshzt ? formData.djshzt : null,
          djrq: formData.djrq ? formData.djrq + ' 00' + ":" + '00' + ":" + '00' : null,
          djrq_to: formData.djrq_to ? formData.djrq_to + ' 23' + ":" + '59' + ":" + '59' : null,
          ckbm: formData.ckbm ? formData.ckbm : null,
          type: '0'//入库0出库1
        },
        paramsMap: {},
        column: '',
        order: ''
      }
      const isRead = util.isReadModel()
      if (isRead) {
        return godownEntryApi.getShpage(queryParams)
      } else {
        return godownEntryApi.page(queryParams)
      }
    },
    addRowModal() {
      this.$refs.godownEntry.showDialog()
    },
    editRowModal() {
      const rowArr = this.$refs.xGrid.getCheckboxRecords(true);
      if (rowArr && rowArr.length === 1) {
        if (rowArr[0].djshzt === '0' || rowArr[0].djshzt === '20') {
          this.$refs.godownEntry.showDialog(true, rowArr[0], false)
        } else {
          VXETable.modal.confirm({
            content: '包含待审核或归档状态数据\n请重新选择记录',
            title: '操作异常',
            status: 'error'
          })
        }
      } else {
        VXETable.modal.confirm({content: '有且只能够操作一条记录\n请选择一条记录', title: '操作异常', status: 'error'})
      }
    },
    handleDelete() {
      const rowsArr = this.$refs.xGrid.getCheckboxRecords(true);
      if (rowsArr.length > 0) {
        const rowscheck = []
        var isDelete = true
        rowsArr.map(item => {
          if (item.djshzt === '0' || item.djshzt === '20') {
            rowscheck.push(item.id)
          } else {
            isDelete = false
            return isDelete
          }
        })
        if (isDelete) {
          rowsArr.forEach((item) => {
            if (item.cjrbm !== this.LanderId) {
              this.$confirm('此操作包括非当前登陆人创建工单, 是否继续?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
              }).then(() => {
                let queryParams = rowscheck
                godownEntryApi.delete(queryParams).then(res => {
                  if (res.code === '200') {
                    this.$message.success(res.message)
                    this.$refs.xGrid.commitProxy('query')
                  }
                })
              }).catch(() => {
                this.$message({
                  type: 'info',
                  message: '已取消删除!'
                });
              });
            } else {
              this.$confirm('此操作将进行删除操作, 是否继续?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
              }).then(() => {
                let queryParams = rowscheck
                godownEntryApi.delete(queryParams).then(res => {
                  if (res.code === '200') {
                    this.$message.success(res.message)
                    this.$refs.xGrid.commitProxy('query')
                  }
                })
              }).catch(() => {
                this.$message({
                  type: 'info',
                  message: '已取消删除!'
                });
              });
            }
          })
        } else {
          VXETable.modal.confirm({
            content: '包含待审核或归档状态数据\n请重新选择记录',
            title: '操作异常',
            status: 'error'
          })
        }
      } else {
        this.$message.warning('请先勾选数据，再进行删除操作')
      }
    },
    handleAuditall() { //批量提交审核的方法
      const rowsArr = this.$refs.xGrid.getCheckboxRecords(true);
      if (rowsArr.length > 0) {
        const rowscheck = []
        var isAudit = true
        rowsArr.map(item => {
          if (item.djshzt !== '0') {
            isAudit = false
            return isAudit
          } else {
            rowscheck.push(item.id)
          }
        })
        if (isAudit) {
          this.$confirm('此操作将进行批量审核操作, 是否继续?', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }).then(() => {
            let queryParams = rowscheck
            godownEntryApi.submitShByIds(queryParams).then(res => {
              if (res.code === '200') {
                this.$message.success(res.message)
                this.$refs.xGrid.commitProxy('query')
              }
            })
          }).catch(() => {
            this.$m({
              type: 'info',
              message: '已取消批量审核!'
            });
          });
        } else {
          VXETable.modal.confirm({
            content: '包含不可进行提交审核操作数据\n请重新选择记录',
            title: '操作异常',
            status: 'error'
          })
        }
      } else {
        this.$message.warning('请先勾选数据，再进行批量提交操作')
      }
    },
    handleAudit(row) { //提交审核的方法
      const isRead = util.isReadModel()
      if (isRead) {
        this.$refs.auditEquipment.showDialog(true, row.row)
      } else {
        this.$confirm('确实要提交审核吗, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          const rowcheck = []
          rowcheck.push(row.row.id)
          let queryParams = rowcheck
          godownEntryApi.submitShByIds(queryParams).then(res => {
            if (res.code === '200') {
              this.$message.success(res.message)
              this.$refs.xGrid.commitProxy('query')
            }
          })
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消提交!'
          });
        });

      }
    },
    handleAuditPass(val) {
      this.$refs.godownEntry.showDialog(true, val, true)
    },
    handleAuditList(val) {
      this.$refs.equipmentList.showDialog(true, val)
    },
    closeEvent() {
      this.$refs.xGrid.commitProxy('query')
    },
    closeShEvent() {
      this.$refs.xGrid.commitProxy('query')
    }
  }
}
// 创建一个简单的工具栏-左侧按钮渲染
VXETable.renderer.add('add', {
  renderToolbarButton(h, renderOpts, params) {
    const {events = {}} = renderOpts
    const {button, $table} = params
    return [
      <vxe-button icon="fa fa-plus (alias)" content="创建入库单" onClick={
        () => {
          events.click(button)
        }
      }></vxe-button>
    ]
  }
})

// 创建一个简单的工具栏-左侧按钮渲染
VXETable.renderer.add('edit', {
  renderToolbarButton(h, renderOpts, params) {
    const {events = {}} = renderOpts
    const {button, $table} = params
    return [
      <vxe-button icon="fa fa-edit (alias)" content="修改" onClick={
        () => {
          events.click(button)
        }
      }></vxe-button>
    ]
  }
})
// 创建一个简单的工具栏-左侧按钮渲染
VXETable.renderer.add('delete', {
  renderToolbarButton(h, renderOpts, params) {
    const {events = {}} = renderOpts
    const {button, $table} = params
    return [
      <vxe-button icon="fa fa-times (alias)" content="删除" onClick={
        () => {
          events.click(button)
        }
      }></vxe-button>
    ]
  }
})
// 创建一个简单的工具栏-左侧按钮渲染
VXETable.renderer.add('audit', {
  renderDefault(h, renderOpts, params) {
    const {events = {}} = renderOpts
    const {row, column} = params
    const isRead = util.isReadModel()

    if (isRead) {
      return [
        // disabled={row.djshzt === '10' ? false : true} type={row.djshzt === '10'?'primary':'info'}
        <el-button disabled={row.djshzt === '10' ? false : true} type={row.djshzt === '10' ? 'primary' : 'info'}
                   size="mini" onClick={
          () => {
            events.click(params)
          }
        }>审核</el-button>
      ]

    } else {

      return [
        <el-button disabled={(row.djshzt === '0' || row.djshzt === '20') ? false : true}
                   type={(row.djshzt === '0' || row.djshzt === '20') ? 'primary' : 'info'} size="mini" onClick={
          () => {
            events.click(params)
          }
        }>提交审核</el-button>
      ]

    }
  }
})
//入库编号穿透渲染
VXETable.renderer.add('rkdh', {
  renderDefault(h, renderOpts, params) {
    const {events = {}} = renderOpts
    const {row, column} = params
    return [
      <span style="color:#0000FF;cursor: pointer;" onClick={
        () => {
          events.click(params.row)
        }
      }>{params.row.id}</span>
    ]
  }
})
//入库数量穿透渲染
VXETable.renderer.add('sl', {
  renderDefault(h, renderOpts, params) {
    const {events = {}} = renderOpts
    const {row, column} = params
    return [
      <span style="color:#0000FF;cursor: pointer;" onClick={
        () => {
          events.click(params.row)
        }
      }>{params.row.sl}</span>
    ]
  }
})
// 批量
// 创建一个简单的工具栏-左侧按钮渲染
VXETable.renderer.add('auditall', {
  renderToolbarButton(h, renderOpts, params) {
    const {events = {}} = renderOpts
    const {row, column} = params
    return [
      <vxe-button icon="fa fa-check" content="批量提交" onClick={
        () => {
          events.click(params)
        }
      }></vxe-button>
    ]
  }
})
// 创建一个简单的工具栏-左侧按钮渲染
VXETable.renderer.add('auditpass', {
  renderToolbarButton(h, renderOpts, params) {
    const {events = {}} = renderOpts
    const {button, $table} = params
    return [
      <vxe-button icon="fa fa-check" content="审核" onClick={
        () => {
          events.click(button)
        }
      }></vxe-button>
    ]
  }
})
</script>

<style scoped>

</style>
